import json
import sys
import os
from utils.log_util import prints, getLogeFilePath
from constant.globl_constant import fibList, fibList2, fibList3, strategyList
from constant.globl_constant import mvSingal, indicatorSignal, strategyList
from flask import Flask
from utils.time_util import current_time
from worker.base.base_worker import BaseWorker
from constant.globl_constant import titleDict

sys.stdout = open(os.devnull, "w")


class WebWorker(BaseWorker):

    app = Flask(__name__)
    currentSupper = {}

    def startServer(self):
        """
        启动Flask
        """

        prints("web服务已启动...")
        self.app.debug = False  # 设置调试模式，生产模式的时候要关掉debug
        self.app.run(host="0.0.0.0", port=80)
        #app.run(port=80)

    @app.route('/test', methods=['GET'])
    def test():
        return "test"

    @app.route('/importantPoint', methods=['GET'])
    def point():
        """
        支撑阻力
        """
        buyPriceArr = []
        buyTpPriceArr = []
        sellPriceArr = []
        sellTpPriceArr = []

        listValue = sorted([
            int(item * 100) / 100 for item in (fibList + fibList2 + fibList3)
        ],
                           reverse=True)

        if len(strategyList) != 0:
            if "buy" in strategyList[0]:
                strategyBuy = strategyList[0]["buy"]
                if len(strategyBuy) != 0:
                    if "price" in strategyBuy:
                        buyPriceArr = strategyBuy["price"]
                    if "tp" in strategyBuy:
                        buyTpPriceArr = strategyBuy["tp"]

            if "sell" in strategyList[0]:
                strategySell = strategyList[0]["sell"]
                if len(strategySell) != 0:
                    if "price" in strategySell:
                        sellPriceArr = strategySell["price"]
                    if "tp" in strategySell:
                        sellTpPriceArr = strategySell["tp"]

        allPrice = sorted((buyPriceArr + sellPriceArr) + listValue,
                          reverse=True)

        for index in range(len(allPrice) - 1, -1, -1):
            lastValue = allPrice[index]
            for nextIndex in range(index - 1, -1, -1):
                nextValue = allPrice[nextIndex]
                if abs(lastValue - nextValue) < 2:
                    allPrice[index] = nextValue
                    lastValue = nextValue

        signal = 0
        if len(mvSingal) != 0 and len(indicatorSignal) != 0:
            mvState = mvSingal[0]
            indicatorState = indicatorSignal[0]
            if current_time() - mvState[0] <= 60 and current_time(
            ) - indicatorState[0] <= 60:
                if mvState[1] is True and indicatorState[1] is True:
                    signal = 1  #看涨
                elif mvState[1] is False and indicatorState[1] is False:
                    signal = 2  #看跌

        listPriceList = sorted(list(set(allPrice)), reverse=True)
        if len(listPriceList) != 0:
            strList = [str(num) for num in listPriceList]
            return "_".join(strList) + "&" + str(signal)
        return ""

    @app.route('/title', methods=['GET'])
    def titleInfo():
        """
        标题策略
        """

        if len(titleDict) != 0:
            a = [str(value) for key, value in titleDict["a"].items()]
            b = {key: value for key, value in titleDict["b"].items()}
            titleDict.clear()
            return "|".join(a) + "&" + json.dumps(b)
        return ""


if __name__ == '__main__':
    WebWorker().startServer()